﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FremtidensPlejehjem_Server.Database
{
    public static class DbGeneral
    {
        public static string GetConnectionString()
        {
            string connString = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;

            return connString;
        }

        public static int GetNextId(string idColumnName, string tableName)
        {
            string query = "SELECT TOP 1 " + idColumnName + " FROM " + tableName + " ORDER BY " + idColumnName + " DESC";

            using (SqlConnection conn = new SqlConnection(DbGeneral.GetConnectionString()))
            {
                try
                {
                    SqlCommand cmd = new SqlCommand();

                    cmd.CommandText = query;
                    cmd.Connection = conn;
                    cmd.CommandType = CommandType.Text;

                    int id = 1;

                    conn.Open();

                    SqlDataReader dr = cmd.ExecuteReader();

                    dr.Read();

                    if (dr.HasRows)
                        id += dr.GetInt32(0);

                    conn.Close();

                    return id;
                }
                catch (SqlException e)
                {
                    //Insert Logging Here
                    throw;
                }
            }
        }
    }
}
